import type { RouteRecordRaw } from 'vue-router';
let firstMenu: any = null;
export function mapMenuToRoute(userMenus: any[]): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = [];
  /* 拿到所有的路由路径 */
  const allRoutes: RouteRecordRaw[] = [];
  require
    .context('../router/main', true, /\.ts$/)
    .keys()
    .forEach((item) => {
      //拿到每一个路由的导出模块
      const route = require('../router/main' + item.split('.')[1]);
      //取到每一个导出模块对应的对象放到allRoutes里面去。
      allRoutes.push(route.default);
    });
  /* 将路由路径和usermenus里面的路径做匹配 */
  function _recurseGetRoute(menus: any[]) {
    menus.forEach((item: any) => {
      if (item.type == 2) {
        const route = allRoutes.find((routePath) => routePath.path == item.url);
        if (route) routes.push(route);
        /* 获取第一个菜单 */
        if (!firstMenu) {
          firstMenu = item;
        }
      } else {
        _recurseGetRoute(item.children);
      }
    });
  }
  _recurseGetRoute(userMenus);
  return routes;
}
/* 实现面包屑 */
import { IBreadType } from '@/base-ui/breadCrumb/src/type';
export function breadCrumbPath(
  usermenus: any[],
  currentPath: string
): IBreadType[] {
  const breadPath: IBreadType[] = [];
  _recurseGetId(usermenus, currentPath, breadPath);
  return breadPath;
}
/* 传过来usermenus和当前路径，匹配url对应的id */
export function _recurseGetId(
  usermenus: any[],
  currentPath: string,
  breadPath?: any[]
): any {
  for (const item of usermenus) {
    if (item.type === 2 && currentPath == item.url) {
      return item;
    } else if (item.type == 1) {
      const menu = _recurseGetId(item.children ?? [], currentPath);
      if (menu) {
        breadPath?.push({ name: item.name, path: item.url });
        breadPath?.push({ name: menu.name, path: menu.url });
        return menu.id;
      }
    }
  }
}
/* 拿到用户的所有权限并返回 */
function mapMenusToPermissions(userMenus: any[]) {
  const permissions: any[] = [];
  const _mapMenusToPermissions = (userMenus: any[]) => {
    for (const item of userMenus) {
      // debugger;
      if (item.type == 3) {
        permissions.push(item.permission);
      } else {
        _mapMenusToPermissions(item.children ?? []);
      }
    }
  };
  _mapMenusToPermissions(userMenus);
  return permissions;
}
export { firstMenu, mapMenusToPermissions };
